// threadpool.c - 实现线程池功能
#include "../include/threadpool.h"
#include "../include/header.h"


// 线程工作函数
static void *threadpool_worker(void *arg);

// 创建线程池
threadpool_t* threadpool_create(int thread_count, int queue_size) {
    threadpool_t *pool = (threadpool_t *)malloc(sizeof(threadpool_t));
    if (!pool) return NULL;
    
    // 初始化线程池参数
    pool->thread_count = thread_count;
    pool->queue_size = queue_size;
    pool->head = pool->tail = pool->count = pool->shutdown = 0;
    
    // 分配线程和任务队列的内存
    pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
    pool->task_queue = (threadpool_task_t *)malloc(sizeof(threadpool_task_t) * queue_size);
    if (!pool->threads || !pool->task_queue) {
        free(pool);
        return NULL;
    }
    
    // 初始化互斥锁和条件变量
    pthread_mutex_init(&(pool->lock), NULL);
    pthread_cond_init(&(pool->notify), NULL);
    
    // 创建线程
    for (int i = 0; i < thread_count; i++) {
        pthread_create(&(pool->threads[i]), NULL, threadpool_worker, (void *)pool);
    }
    
    return pool;
}

// 向线程池中添加任务
int threadpool_add(threadpool_t *pool, void (*function)(void *), void *argument) {
    pthread_mutex_lock(&(pool->lock));
    
    int next = (pool->tail + 1) % pool->queue_size;
    // 如果任务队列已满，直接返回失败
    if (pool->count == pool->queue_size) {
        pthread_mutex_unlock(&(pool->lock));
        return -1;
    }
    
    // 添加任务到任务队列
    pool->task_queue[pool->tail].function = function;
    pool->task_queue[pool->tail].argument = argument;
    pool->tail = next;
    pool->count++;
    
    // 唤醒等待的线程
    pthread_cond_signal(&(pool->notify));
    pthread_mutex_unlock(&(pool->lock));
    return 0;
}

// 销毁线程池
int threadpool_destroy(threadpool_t *pool) {
    pthread_mutex_lock(&(pool->lock));
    pool->shutdown = 1;
    pthread_cond_broadcast(&(pool->notify)); // 唤醒所有线程
    pthread_mutex_unlock(&(pool->lock));
    
    // 等待所有线程结束
    for (int i = 0; i < pool->thread_count; i++) {
        pthread_join(pool->threads[i], NULL);
    }
    
    // 释放资源
    free(pool->threads);
    free(pool->task_queue);
    pthread_mutex_destroy(&(pool->lock));
    pthread_cond_destroy(&(pool->notify));
    free(pool);
    
    return 0;
}

// 线程工作函数，从任务队列中取出任务执行
static void *threadpool_worker(void *arg) {
    threadpool_t *pool = (threadpool_t *)arg;
    
    while (1) {
        pthread_mutex_lock(&(pool->lock));
        
        // 如果任务队列为空且未关闭，则等待
        while (pool->count == 0 && !pool->shutdown) {
            pthread_cond_wait(&(pool->notify), &(pool->lock));
        }
        
        // 线程池关闭，退出循环
        if (pool->shutdown) {
            pthread_mutex_unlock(&(pool->lock));
            break;
        }
        
        // 取出任务
        threadpool_task_t task = pool->task_queue[pool->head];
        pool->head = (pool->head + 1) % pool->queue_size;
        pool->count--;
        pthread_mutex_unlock(&(pool->lock));
        
        // 执行任务
        (*(task.function))(task.argument);
    }
    return NULL;
}
